package com.jsz.peini.interceptor;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jsz.peini.common.util.PeiniUtils;
import com.jsz.peini.common.util.SpringContextUtil;
import com.jsz.peini.common.util.ThreadUtil;
import com.jsz.peini.mapper.user.UserInfoMapper;
import com.jsz.peini.vo.ThreadInfo;

public class UserActiveMonitorFilter implements Filter{
	Logger logger = LoggerFactory.getLogger(UserActiveMonitorFilter.class);
	UserInfoMapper mapper;
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		ThreadUtil.init();
		if(mapper == null){
			mapper = (UserInfoMapper)SpringContextUtil.getBean(UserInfoMapper.class);
		}
		String token = ((HttpServletRequest)request).getHeader("token");
		String xpointStr = ((HttpServletRequest)request).getHeader("xpoint");
		String ypointStr = ((HttpServletRequest)request).getHeader("ypoint");
		
		refreshUserAlive(token, xpointStr, ypointStr);
		chain.doFilter(request, response);
		
	}

	@Override
	public void destroy() {
		
	}
	
	
	public static Map<String,Long> userAccessMap = new ConcurrentHashMap<String,Long>();
	private void refreshUserAlive(String token, String xpointStr, String ypointStr) {
		try {
			if (token == null)
				return;
			String userId = PeiniUtils.validToken(token).getString("userId");
			if (userId == null)
				return;
			Double xpoint = null;
			Double ypoint = null;
			if (xpointStr != null && ypointStr != null){
				xpoint = Double.parseDouble(xpointStr);
				ypoint = Double.parseDouble(ypointStr);
			}
			ThreadUtil.getThreadInfo().setUserId(userId);
			ThreadUtil.getThreadInfo().setXpoint(xpoint);
			ThreadUtil.getThreadInfo().setYpoint(ypoint);
			Long lastAccessTime = userAccessMap.get(token);
			userAccessMap.put(token, System.currentTimeMillis());
			if (lastAccessTime == null || (lastAccessTime + 60000) < System.currentTimeMillis()) {
				mapper.updateUserActive(userId, xpoint, ypoint);
			}
		} catch (Throwable t) {
			logger.error(t.getMessage(), t);
		}
	}

}
